<template>
  <div class="voice-recognizer">
    <!-- 自定义按钮样式或使用默认样式 -->
    <slot name="button" 
          :is-listening="isListening" 
          :start-listening="startListening" 
          :stop-listening="stopListening">
      <button 
        class="record-button" 
        :class="[buttonClass, { 'recording': isListening }]"
        @mousedown="startListening" 
        @mouseup="stopListening"
        @mouseleave="stopListening"
        :style="buttonStyle"
      >
        {{ isListening ? recordingText : defaultText }}
      </button>
    </slot>
    
    <!-- 可选的状态显示 -->
    <slot name="status" :is-listening="isListening" :is-processing="isProcessing">
      <div v-if="showStatus" class="status">
        <span v-if="isListening" class="listening-status">{{ recordingText }}</span>
        <span v-else-if="isProcessing" class="processing-status">{{ processingText }}</span>
        <span v-else>{{ defaultText }}</span>
      </div>
    </slot>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';

// 定义组件接收的属性
const props = defineProps({
  // 按钮文本配置
  defaultText: {
    type: String,
    default: '按住说话'
  },
  recordingText: {
    type: String,
    default: '正在录音...'
  },
  processingText: {
    type: String,
    default: '正在处理...'
  },
  
  // 样式配置
  buttonClass: {
    type: [String, Object, Array],
    default: ''
  },
  buttonStyle: {
    type: Object,
    default: () => ({})
  },
  showStatus: {
    type: Boolean,
    default: false
  },
  
  // 语音识别配置
  language: {
    type: String,
    default: 'zh-CN'
  }
});

// 定义事件
const emit = defineEmits([
  'recognition-start',     // 开始识别
  'recognition-end',       // 结束识别
  'text-recognized',       // 文字识别完成
  'error'                  // 错误事件
]);

// 内部状态
const isListening = ref(false);
const isProcessing = ref(false);
const recognition = ref(null);
const lastRecognizedText = ref('');
const tempTranscript = ref('');      // 临时存储识别过程中的文本
const finalTranscript = ref('');     // 存储最终文本

// 初始化语音识别
const initSpeechRecognition = () => {
  // 检查浏览器兼容性
  if (!('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)) {
    emit('error', {
      type: 'browser-support',
      message: '您的浏览器不支持语音识别功能，请使用Chrome等现代浏览器'
    });
    return false;
  }
  
  // 清理之前的实例
  cleanup();
  
  // 创建语音识别对象
  const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  recognition.value = new SpeechRecognition();
  
  // 基础设置
  recognition.value.lang = props.language;
  recognition.value.continuous = false;  // 设为false，每次只进行一次完整的识别
  recognition.value.interimResults = true;
  
  // 结果处理函数
  recognition.value.onresult = (event) => {
    let currentText = '';
    let isFinal = false;
    
    // 获取最新的识别结果
    for (let i = event.resultIndex; i < event.results.length; i++) {
      currentText = event.results[i][0].transcript;
      isFinal = event.results[i].isFinal;
      
      if (isFinal) {
        // 如果是最终结果，添加到finalTranscript
        if (currentText && !isDuplicateText(currentText)) {
          finalTranscript.value += currentText + ' ';
          lastRecognizedText.value = currentText;
        }
      } else {
        // 临时结果
        tempTranscript.value = currentText;
      }
    }
  };
  
  // 结束事件
  recognition.value.onend = () => {
    if (isListening.value) {
      // 如果用户仍在按住按钮，重新启动识别
      setTimeout(() => {
        try {
          recognition.value.start();
        } catch (e) {
          console.error('重新启动语音识别失败:', e);
        }
      }, 100);
    } else {
      // 用户松开按钮，识别结束
      isProcessing.value = false;
      
      // 将临时结果也添加到最终结果（如果有）
      if (tempTranscript.value && !isDuplicateText(tempTranscript.value)) {
        finalTranscript.value += tempTranscript.value + ' ';
      }
      
      // 发送最终识别结果给父组件
      if (finalTranscript.value.trim()) {
        emit('text-recognized', finalTranscript.value.trim());
      }
      
      // 重置状态
      tempTranscript.value = '';
      finalTranscript.value = '';
      lastRecognizedText.value = '';
    }
  };
  
  // 错误处理
  recognition.value.onerror = (event) => {
    console.error('语音识别错误:', event.error);
    if (event.error === 'no-speech') {
      // 无语音输入，继续监听
      if (isListening.value) {
        setTimeout(() => recognition.value.start(), 100);
      }
    } else {
      isListening.value = false;
      isProcessing.value = false;
      
      emit('error', {
        type: 'recognition-error',
        message: `语音识别错误: ${event.error}`,
        error: event
      });
    }
  };
  
  return true;
};

// 检查文本是否重复
const isDuplicateText = (newText) => {
  if (!newText) return true;
  
  // 去除首尾空格后比较
  newText = newText.trim();
  const existingText = finalTranscript.value.trim();
  
  // 检查是否与上次识别的文本相同或者是现有文本的子集
  if (newText === lastRecognizedText.value) return true;
  if (existingText.endsWith(newText)) return true;
  
  // 将新文本按词分割，检查最后几个词是否重复
  const words = newText.split(/\s+/);
  if (words.length > 1) {
    const lastTwoWords = words.slice(-2).join(' ');
    if (existingText.endsWith(lastTwoWords)) {
      return true;
    }
  }
  
  return false;
};

// 清理资源
const cleanup = () => {
  if (recognition.value) {
    try {
      recognition.value.stop();
    } catch (e) {
      // 忽略可能的错误
    }
    recognition.value = null;
  }
  
  tempTranscript.value = '';
  finalTranscript.value = '';
  lastRecognizedText.value = '';
};

// 开始语音识别
const startListening = () => {
  if (isListening.value) return;
  
  // 初始化识别器
  if (!recognition.value && !initSpeechRecognition()) {
    return;
  }
  
  // 重置状态
  tempTranscript.value = '';
  finalTranscript.value = '';
  lastRecognizedText.value = '';
  isListening.value = true;
  
  // 开始识别
  try {
    recognition.value.start();
    emit('recognition-start');
  } catch (e) {
    console.error('启动语音识别失败:', e);
    
    // 尝试重新初始化并启动
    if (initSpeechRecognition()) {
      setTimeout(() => {
        try {
          recognition.value.start();
          emit('recognition-start');
        } catch (error) {
          isListening.value = false;
          emit('error', {
            type: 'start-error',
            message: '无法启动语音识别',
            error
          });
        }
      }, 200);
    }
  }
};

// 停止语音识别
const stopListening = () => {
  if (!isListening.value) return;
  
  isListening.value = false;
  isProcessing.value = true;
  
  try {
    if (recognition.value) {
      recognition.value.stop();
      emit('recognition-end');
    }
  } catch (e) {
    console.error('停止语音识别失败:', e);
    isProcessing.value = false;
  }
};

// 暴露组件方法给父组件
defineExpose({
  startListening,
  stopListening
});

onMounted(() => {
  // 组件挂载时，不主动初始化识别器，等待用户交互
});

onUnmounted(() => {
  // 组件卸载前清理资源
  cleanup();
});
</script>

<style scoped>
.voice-recognizer {
  display: inline-block;
}

.record-button {
  padding: 1rem 2rem;
  font-size: 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  user-select: none;
}

.record-button.recording {
  background-color: #f44336;
  animation: pulse 1.5s infinite;
}

.status {
  margin-top: 0.5rem;
  font-size: 14px;
  color: #666;
}

.listening-status {
  color: #f44336;
  font-weight: bold;
}

.processing-status {
  color: #ff9800;
  font-weight: bold;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}
</style>
